import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/MessageHistorySearchDayPage.dart';
import 'package:im_app/im/page/view/ContentSearchView.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/component/SessionIconView.dart';
import 'package:im_app/im/util/DateUtil.dart';

import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../bloc/MessageHistoryCubit.dart';

class MessageHistorySearchPage extends StatefulWidget {
  final ImSession session;

  const MessageHistorySearchPage({required this.session, super.key});

  @override
  State<StatefulWidget> createState() => _MessageHistoryState();
}

class _MessageHistoryState extends State<MessageHistorySearchPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String _search = '';

  @override
  void initState() {
    super.initState();
    this._tabController = new TabController(length: 5, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    var messageHistoryCubit = context.watch<MessageHistoryCubit>();
    return Scaffold(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: SafeArea(
          child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(top: 20, left: 10, right: 10),
            child: ContentSearchView(
              prefix: messageHistoryCubit.state.prefix,
              searchHandler: this.search,
            ),
          ),
          Expanded(
              child: messageHistoryCubit.state.search == '' && messageHistoryCubit.state.prefix == ''
                  ? _buildDefaultPane(context)
                  : _buildSearchResultPane(messageHistoryCubit))
        ],
      )),
    );
  }

  Widget _buildDefaultPane(BuildContext context) {
    var messageHistoryCubit = context.watch<MessageHistoryCubit>();
    return Padding(
      padding: EdgeInsets.only(top: 100),
      child: Column(
        children: [
          const Padding(
            padding: EdgeInsets.only(bottom: 20),
            child: Center(
              child: Text(
                '搜索指定内容',
                style: TextStyle(color: Colors.grey),
              ),
            ),
          ),
          Expanded(
              child: GridView(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 5),
            children: [
              _buildDaySearchCell(),
              _buildDefaultSearchCell(messageHistoryCubit, '图片和视频', [ImMessageType.Image, ImMessageType.Video]),
              _buildDefaultSearchCell(messageHistoryCubit, '文件', [ImMessageType.File]),
              _buildDefaultSearchCell(messageHistoryCubit, '链接', [ImMessageType.Url]),
              _buildDefaultSearchCell(messageHistoryCubit, '音乐和音频', [ImMessageType.Audio]),
            ],
          ))
        ],
      ),
    );
  }

  Widget _buildSearchResultPane(MessageHistoryCubit messageHistoryCubit) {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.only(left: 10, top: 10, bottom: 5),
          height: 45,
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: [
              SizedBox(
                height: 30,
                width: 50,
                child: _buildDefaultSearchCell(messageHistoryCubit, '全部', []),
              ),
              SizedBox(
                height: 30,
                width: 100,
                child:
                    _buildDefaultSearchCell(messageHistoryCubit, '图片和视频', [ImMessageType.Image, ImMessageType.Video]),
              ),
              SizedBox(
                height: 30,
                width: 50,
                child: _buildDefaultSearchCell(messageHistoryCubit, '文件', [ImMessageType.File]),
              ),
              SizedBox(
                height: 30,
                width: 50,
                child: _buildDefaultSearchCell(messageHistoryCubit, '链接', [ImMessageType.Url]),
              ),
              SizedBox(
                height: 30,
                width: 100,
                child: _buildDefaultSearchCell(messageHistoryCubit, '音乐和音频', [ImMessageType.Audio]),
              ),
            ],
          ),
        ),
        Expanded(
            child: Container(
          color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
          child: ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              var message = messageHistoryCubit.state.results.elementAt(index);
              return _buildMessagePane(message);
            },
            itemCount: messageHistoryCubit.state.results.length,
            separatorBuilder: (BuildContext context, int index) {
              return ListSeparator(
                indent: 10,
              );
            },
          ),
        ))
      ],
    );
  }

  Widget _buildMessagePane(ImMessage message) {
    return Container(
        height: 40,
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.only(right: 10),
              child: SessionIconView(session: message.imSession!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
            ),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(message.fromImUser?.userName ?? '', style: const TextStyle(color: Colors.grey),),
                Text(message.content),
              ],
            )),
            Text(DateUtil.sessionShowTime(message.serverReceiveTime) ?? ''),
          ],
        ));
  }

  Widget _buildDaySearchCell() {
    return InkWell(
      child: const Center(
        child: Text(
          '日期',
        ),
      ),
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return MessageHistorySearchDayPage(session: this.widget.session);
        }));
      },
    );
  }

  Widget _buildDefaultSearchCell(
      MessageHistoryCubit messageHistoryCubit, String name, List<ImMessageType> messageTypes) {
    return InkWell(
      child: Center(
        child: Text(name),
      ),
      onTap: () {
        messageHistoryCubit.add(MessageHistoryTypeEvent(name, messageTypes));
      },
    );
  }

  void search(BuildContext context, String searchMessage) {
    _search = searchMessage;
    Future.delayed(const Duration(milliseconds: 500), () {
      if (_search == searchMessage) {
        var messageHistoryCubit = BlocProvider.of<MessageHistoryCubit>(context, listen: false);
        messageHistoryCubit.add(MessageHistorySearchEvent(searchMessage));
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    this._tabController.dispose();
  }
}
